<?php

namespace App\Http\Middleware;

use Closure;
//use Encore\Admin\Facades\Admin;

class IsLogin
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
//        config(['auth.defaults.guard' => 'admin']);
//        $redirectTo = admin_base_path(config('admin.auth.redirect_to', 'login'));
        //未登录： 并且uri 不在指定的数组中，须跳转到登录页面
        if (auth()->guest() && !$this->shouldPassThrough($request) ) {
//            return redirect()->to($redirectTo);
            return response()->json(
                ['status' => false, 'code' => 403, 'message' => 'token过期请重新登录！'],
                403
            );
        }
        // 已经登入：跳转到首页
        /*if (auth()->user() && $request->path() == trim($redirectTo,'/') ) {

            return redirect('/');
        }*/
        return $next($request);
    }

    /**
     * Determine if the request has a URI that should pass through verification.
     *
     * @param \Illuminate\Http\Request $request
     *
     * @return bool
     */
    protected function shouldPassThrough($request)
    {

        $excepts = ['login', 'logout'];
        return collect($excepts)
            ->map('admin_base_path')
            ->contains(function ($except) use ($request) {
                if ($except !== '/') {
                    $except = trim($except, '/');
                }

                return $request->is($except);
            });

    }
}
